package wx

import (
	"xlq-demo/library/config"
	"xlq-demo/library/util"
	"net/http"
	"fmt"
	"time"
	"github.com/tidwall/gjson"
)

type accessToken struct {
	AccessToken string
	ExpireAt int64
}

var (
	//工作人员微信小程序access_token
	workerAppAccessToken *accessToken

	//公众号access_token
	mpAccessToken *accessToken
)

//获取工作人员小程序access_token
func GetWorkerAppAccessToken() (string,error) {
	if workerAppAccessToken == nil {
		workerAppAccessToken = new(accessToken)
	}
	if workerAppAccessToken.ExpireAt > time.Now().Unix() + 3 {
		return workerAppAccessToken.AccessToken,nil
	}
	url := "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+config.Config.WxMine.AppId+"&secret="+config.Config.WxMine.AppSecret
	code,resBody,err := util.HttpRequest("GET",url,nil,nil)
	if err != nil || code != http.StatusOK {
		fmt.Println("获取工作人员小程序access_token失败,http失败",code,err)
		return "",fmt.Errorf("获取工作人员小程序access_token失败")
	}
	//读取内容
	resObj := gjson.ParseBytes(resBody)

	//判断是否存在报错
	if resObj.Get("errcode").Exists() {
		fmt.Println("获取工作人员小程序access_token报错",string(resBody))
		return "",fmt.Errorf("获取工作人员小程序access_token报错")
	}

	//获取accessToken
	accessToken := resObj.Get("access_token").String()
	expireAt := time.Now().Unix() + resObj.Get("expires_in").Int()

	workerAppAccessToken.AccessToken = accessToken
	workerAppAccessToken.ExpireAt = expireAt

	return accessToken,nil
}

//获取公众号 access_token
func GetMpAccessToken() (string,error) {
	if mpAccessToken == nil {
		mpAccessToken = new(accessToken)
	}
	if mpAccessToken.ExpireAt > time.Now().Unix() + 3 {
		return mpAccessToken.AccessToken,nil
	}

	url := "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+config.Config.WxMp.AppId+"&secret="+config.Config.WxMp.AppSecret
	code,resBody,err := util.HttpRequest("GET",url,nil,nil)
	if err != nil || code != http.StatusOK {
		fmt.Println("获取公众号access_token失败,http失败",code,err)
		return "",fmt.Errorf("获取公众号access_token失败")
	}
	//读取内容
	resObj := gjson.ParseBytes(resBody)

	//判断是否存在报错
	if resObj.Get("errcode").Exists() {
		fmt.Println("获取公众号access_token报错",string(resBody))
		return "",fmt.Errorf("获取公众号access_token报错")
	}

	//获取accessToken
	accessToken := resObj.Get("access_token").String()
	expireAt := time.Now().Unix() + resObj.Get("expires_in").Int()

	mpAccessToken.AccessToken = accessToken
	mpAccessToken.ExpireAt = expireAt

	return accessToken,nil
}


